<style>
    .form-controlX{
        border:0px;
        border-bottom: 1px solid gray;
        border-radius: 0px;
        width: auto;
        box-shadow: 0px 0px 0px 0px white;
        padding-left: 10px;
        padding-bottom: 2px;
        margin-bottom: 10px;
    }
    .control-labelX{
        margin-bottom: 10px;
    }
    #centerBody{
        font-size: 12px;
        font-family: "宋体";
    }
    table {
        font-size: 12px;
        vertical-align: center;
        padding: 0px;
    }
    tr {
        border: 1px solid gainsboro;
    }
    tr th {
        text-align: center;
        border: 1px solid gainsboro;
    }
    tr td {
        text-align: center;
        align-self: center;
        padding: 2px;
    }
</style>
<!--编辑组件-->
<div id="PreCustomerOrderEdit" xmlns:v-bind="http://www.w3.org/1999/xhtml" xmlns:v-on="http://www.w3.org/1999/xhtml"  style=" height:100%;margin: 0px;padding: 0px;">
    <div id="bodyFrame"  class="panel panel-default" style="border-radius: 0px;">
        <div id="topBody" class="row rowSet"  style="padding: 0px;text-align: center;padding-top: 10px">
            <div class="col-md-12 column">
                <button type="button" v-on:click="jumpToList()" class="btn btn-link pull-left" >返回</button>
                <!--<br>-->
                <h3 style="margin: 0px"> 客户报货单 </h3>
            </div>
            <!--表单部分-->
            <div class="row rowSet">
                <div v-if="saveDao.orderNo != null">
                    <label for="orderNo" class="col-sm-1 control-labelX" style="text-align: right" >订单号:</label>
                    <div class="col-sm-3" style="text-align: left">
                        <input type="text"  v-model="saveDao.orderNo" class="form-controlX" id="orderNo" readOnly="readonly"/>
                    </div>
                </div>
                <div>
                    <label for="sumQuantity" class="col-sm-1 control-labelX" style="text-align: right" >数量:</label>
                    <div class="col-sm-3"  style="text-align: left">
                        <input type="text"  v-model="saveDao.sumQuantity" class="form-controlX" id="sumQuantity" readOnly="readonly"/>
                    </div>
                </div>

                <div>
                    <label for="customerName" class="col-sm-1 control-labelX" style="text-align: right" >客户名:</label>
                    <div class="col-sm-3" style="text-align: left">
                        <input type="text"  v-model="saveDao.customerName" class="form-controlX" id="customerName"/>
                        <input type="hidden"  v-model="saveDao.customerId"  />
                    </div>
                </div>

                <div>
                    <label for="sendAddress" class="col-sm-1 control-labelX" style="text-align: right" >配送地址:</label>
                    <div class="col-sm-3"  style="text-align: left">
                        <!-- 渲染字典列表 -->
                        <select   v-model="saveDao.customerAddressId" id="sendAddress" class="form-controlX"  @change="changeAddress()">
                            <template v-for="item in addressList" >
                                <option v-if="item.id == saveDao.customerAddressId"  v-bind:value="item.id" selected>{{item.address}}</option>
                                <option v-else v-bind:value="item.id" >{{item.address}}</option>
                            </template>
                        </select>
                    </div>
                </div>

                <div>
                    <label for="sendName" class="col-sm-1 control-labelX" style="text-align: right" >联系人:</label>
                    <div class="col-sm-3"  style="text-align: left">
                        <input type="text"  v-model="saveDao.sendName" class="form-controlX" id="sendName" readOnly="readonly"/>
                    </div>
                </div>

                <div>
                    <label for="sendPhone" class="col-sm-1 control-labelX" style="text-align: right" >联系电话:</label>
                    <div class="col-sm-3"  style="text-align: left">
                        <input type="text"  v-model="saveDao.sendPhone" class="form-controlX" id="sendPhone" readOnly="readonly"/>
                    </div>
                </div>

                <div>
                    <label for="sendType" class="col-sm-1 control-labelX" style="text-align: right" >配送类型:</label>
                    <div class="col-sm-3" style="text-align: left">
                        <!-- 渲染字典列表 -->
                        <select   v-model="saveDao.sendType"  class="form-controlX" id="sendType"  >
                            <template v-for="dictItem in dict.SendType.list" >
                                <option v-if="dictItem.codeCode == saveDao.sendType"  v-bind:value="dictItem.codeCode" selected>{{dictItem.codeValue }}</option>
                                <option v-else v-bind:value="dictItem.codeCode">{{dictItem.codeValue }}</option>
                            </template>
                        </select>
                    </div>
                </div>

                <div>
                    <label for="createUser" class="col-sm-1 control-labelX" style="text-align: right" >制单人:</label>
                    <div class="col-sm-3" style="text-align: left">
                        <input type="text"  v-model="saveDao.createUser" class="form-controlX" id="createUser" readOnly="readonly"/>
                        <input type="hidden"  v-model="saveDao.createUserCode"  />
                    </div>
                </div>

                <div>
                    <label for="madeUser" class="col-sm-1 control-labelX" style="text-align: right" >经办人:</label>
                    <div class="col-sm-3" style="text-align: left">
                        <input type="text"  v-model="saveDao.madeUser" class="form-controlX" id="madeUser"  readOnly="readonly"/>
                        <input type="hidden"  v-model="saveDao.madeUserCode"  />
                    </div>
                </div>

                <div v-if="saveDao.checkUser != null">
                    <label for="checkUser" class="col-sm-1 control-labelX" style="text-align: right" >审核人:</label>
                    <div class="col-sm-3" style="text-align: left">
                        <input type="text"  v-model="saveDao.checkUser" class="form-controlX" id="checkUser" />
                        <input type="hidden"  v-model="saveDao.checkUserCode"  />
                    </div>
                </div>

                <div>
                    <label for="reason" class="col-sm-1 control-labelX" style="text-align: right" >备注:</label>
                    <div class="col-sm-6" style="text-align: left">
                        <input type="text"  v-model="saveDao.reason" class="form-controlX" id="reason" style="width: 100%" />
                    </div>
                </div>
            </div>

            <div  class="row rowSet">
                <!--照片展示列表-->
                <table class="table table-hover table-condensed" align="center" style="margin: 0px">
                    <thead>
                    <tr>
                        <th width="10%">商品图标</th>
                        <th width="20%">商品名称</th>
                        <th width="10%">商品型号</th>
                        <th width="20%">厂商名称</th>
                        <th width="10%">预定数量</th>
                        <th width="10%">库存余量</th>
                        <th width="10%">备注</th>
                        <th width="10%">操作</th>
                    </tr>
                    </thead>
                </table>
            </div>

        </div>
        <div   id="centerBody" class="row rowSet" class="panel-body" style="padding: 0px;">
            <!--体部分-->
            <div class="col-md-12 column" style="margin: 0px;padding: 0px;">
                <!--照片展示列表-->
                <table class=" table-hover table-condensed"   style="vertical-align: center;" >
                    <tbody>
                    <tr v-for="(item,index) in infoDto.itemDaoList">
                        <!--商品图片-->
                        <td align="center" width="10%">
                            <img  :src="$ImageUrl(item.imgId,'small')"   class="img-thumbnail"  width="50px"/>
                        </td>
                        <!--商品名称-->
                        <td valign="center" width="20%">
                            {{item.goodsName}}
                            <input type="hidden" v-model="item.goodsId"/>
                        </td>
                        <!--商品型号-->
                        <td width="10%">
                            <!-- 渲染字典列表 -->
                            <select   v-model="item.goodsModelId" class="form-control"  @change="changeModel(item)">
                                <template v-for="modelItem in item.goodsModelList" >
                                    <option v-if="modelItem.id == item.goodsModelId"  v-bind:value="modelItem.id" selected>{{modelItem.name}}</option>
                                    <option v-else v-bind:value="modelItem.id" >{{modelItem.name}}</option>
                                </template>
                            </select>
                        </td>
                        <!--商品名称-->
                        <td  width="20%">
                            {{item.venderName}}
                            <input type="hidden" v-model="item.venderId"/>
                        </td>
                        <td width="10%">
                            <div class="input-group">
                                <input type="number" v-model="item.quantity" v-on:blur="updateQuantity" class="form-control" />
                                <span class="input-group-addon">({{item.contourName}})</span>
                            </div><!-- /input-group -->
                        </td>
                        <!--库存余量-->
                        <td width="10%">{{item.nowQuantity}}({{item.contourName}})</td>
                        <!--备注-->
                        <td width="10%">
                            <input type="text" v-model="item.note" class="form-control" />
                        </td>
                        <!--操作-->
                        <td width="10%"><button type="button" class="btn btn-link" @click="deleteLine(index)" >删除</button></td>
                    </tr>
                    </tbody>
                </table>
                <!--<hr>-->
                <button type="button" class="btn btn-link" data-toggle="modal" data-target="#goodsSelModal">添加一项</button>
                <button type="button" class="btn btn-link" @click="scanModal()">扫码枪模式</button>
            </div>

        </div>
        <div  id="bottomBody"  style="text-align: center;border-top: 1px solid gainsboro">
            <!--底部-->
            <button type="button" v-on:click="submit(0)" class="btn btn-primary btn-md"   v-if="isShow">保存草稿</button>
            <button type="button" v-on:click="submit(1)" class="btn btn-primary btn-md"   v-if="isShow">提交审核</button>
        </div>
    </div>

    <!-- 扫码模态框（Modal） -->
    <div class="modal fade" id="scanModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="false" data-backdrop="true">
        <div class="modal-dialog">
            <div class="modal-content" >
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="myModalLabel">商品条码扫描</h4>
                </div>
                <div class="modal-body " style="padding: 0px;">
                    <div class="row rowSet" style="padding: 10px 0px 0px 0px;border-bottom: 1px solid gainsboro" >
                        <div class="form-group col-sm-12" style="margin-bottom: 5px;">
                            <div class="input-group">
                                <input type="text"  v-model="barCode" id="barCode"  v-on:keyup="barCodeSel(event)"  class="col-sm-8 form-control"  />
                                <span class="input-group-btn">
                                    <button type="button" class="btn btn-default" v-on:click="queryScan()">条码查询</button>
                                </span>
                            </div><!-- /input-group -->
                        </div>
                    </div><!-- /.row -->
                    <!--展示的结果-->
                    <div class="autoDiv" style="padding: 5px" v-if="barCode.length > 0 && scanResult != null">
                        <div class="panel col-sm-3 column" >
                            <div class="panel-body  " style="padding: 0px; margin: 0px; "   >
                                <img :src="$ImageUrl(scanResult.imgId,'small')" class="img-thumbnail dirImg"/>
                            </div>
                            <div class="panel-footer" style="padding: 0px; margin: 0px;">
                                <span>{{scanResult.goodsName}}</span>
                                <br/>
                                <span>型号:{{scanResult.name}}</span>
                                <br/>
                                <span>当前库存:{{scanResult.quantity}}</span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer" >
                    <div class="form-group col-sm-12" v-if="barCode.length > 0 && scanResult != null">
                        <div class="col-sm-offset-6 col-sm-6 input-group">
                            <span class="input-group-addon">数量：</span>
                            <input type="number"  v-model="scanQuantity" id="scanQuantity"  v-on:keyup="scanQuantityKey(event)"  class="form-control"  />
                            <span class="input-group-addon">({{scanResult.contourName}})</span>
                            <span class="input-group-btn">
                                <button type="button" class="btn btn-primary" v-on:click="scanAdd()">添加此项</button>
                            </span>
                        </div><!-- /input-group -->
                    </div>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>
</div>

<script>
    //采用vue
    var PreCustomerOrderEdit = new Vue({
        el: '#PreCustomerOrderEdit',
        data: {
            //提交的url
            submitUrl: '',
            //根据id查询对象的url
            queryUrl:'',
            //返回查询页面的url
            backUrl:'',
            //根据
            initSaveColumnUrl:Vue.prototype.getUrl('/pageInit/getInitEditPageDto/PreCustomerOrder'),
            saveDao:{
                createUser:mainIndex.userEmployee.name,
                createUserCode:mainIndex.userEmployee.workNo,
                madeUser:mainIndex.userEmployee.name,
                madeUserCode:mainIndex.userEmployee.workNo,
            },
            infoDto:{
                itemDaoList:[]
            },
            initSaveColumnList:[],
            dict:{
                SendType:{ list:[], map:new Map()},
            },
            isEdit : false,
            isShow : true,
            nowSelImageField:'',
            hiddenList:['id','orderNo','checkRemark','state','createDate'],
            //扫码枪改造
            barCode : '',
            scanResult : null,
            scanQuantity :  null,
            //客户地址列表
            addressList:[]
        },
        methods: {
            /**初始化*/
            init:function () {
                var that = this;
                this.$send(this.initSaveColumnUrl,null,function(data){
                    console.log('init执行成功！！'+JSON.stringify(data));
                    for (var i=0;i < data.initSaveColumnList.length;i++) {
                        var item = data.initSaveColumnList[i];
                        for (var j=0;j< that.hiddenList.length;j++) {
                            console.log(that.hiddenList[j] + ' ' +item.fieldName);
                            if(that.hiddenList[j] == item.fieldName) {
                                item.showFlag = false;
                            }
                        }
                    }
                    that.initSaveColumnList = data.initSaveColumnList;
                    that.submitUrl = data.saveUrl;
                    that.queryUrl = data.queryUrl;
                    that.backUrl = data.backUrl;
                    that.dict = data.dict;
                    //加载id对应的数据
                    that.loadEditData();
                });
            },
            jumpToList:function() {
                //加载页面
                loadPageToBodyMain(this.backUrl);
            },
            updateQuantity:function(){
                console.log('change');
                setTimeout(this.updateBalance(),50);
            },
            scanModal: function() {
                //显示
                this.barCode = '';
                $('#scanModal').modal();
                setTimeout(function(){
                    $("#barCode").focus();
                    console.log('获取焦点');
                },500);
            },
            barCodeSel:function(event) {
                //console.log('aaa');
                if (event.keyCode == "13") {
                    if(this.barCode.length > 0) {
                        console.log('回车查询');
                        this.queryScan();
                    }
                }
            },
            scanQuantityKey(event) {
                if (event.keyCode == "13") {
                    this.scanAdd();
                }
            },
            scanAdd:function() {
                if (this.scanQuantity == 0 || this.scanQuantity == null) {
                    alert('数量不能等于0');
                    return;
                }
                let data = this.scanResult;
                var prePurchaseItem = {
                    goodsId:data.parentId,
                    goodsName:data.goodsName,
                    venderName:data.venderName,
                    venderId:data.venderId,
                    contourName:data.contourName,
                    quantity:this.scanQuantity,
                    goodsModelList:[data],
                    goodsModelId:data.id,
                    goodsModelName:data.name,
                    nowQuantity:data.quantity,
                    imgId:data.imgId
                };
                //寻找列表中已经存在的型号
                var haveItem = null;
                for (var i = 0;i < this.infoDto.itemDaoList.length;i++) {
                    var item = this.infoDto.itemDaoList[i];
                    if(item.goodsModelId == data.id) {
                        haveItem = item;
                        break;
                    }
                }
                if (haveItem != null) {
                    if (confirm("存在相同的型号:" + data.goodsName + "[" + data.name + "] 是否加入?")) {
                        //haveItem.quantity=this.scanQuantity;
                        this.$set(haveItem,'quantity',parseFloat(haveItem.quantity) + parseFloat(this.scanQuantity));
                    }
                }else {
                    this.infoDto.itemDaoList.push(prePurchaseItem);
                }
                console.log('加入一条商品');
                this.updateBalance();
                //初始化
                this.scanQuantity  = null;
                this.scanResult = null;
                this.barCode = '';
                $("#barCode").focus();
            },
            queryScan:function() {
                if(this.barCode.length > 0) {
                    //TODO 回写商品选择
                    var that = this;
                    this.$send(this.getUrl('/business/inventory/getGoodsModelInventoryScan/' + this.barCode),null,function (data) {
                        if(data == null || data == '') {
                            alert('无对应条码商品');
                            return;
                        } else {
                            that.scanResult = data;
                            setTimeout(function(){
                                $("#scanQuantity").focus();
                            },50);
                        }
                    });
                }
            },
            /**地址列表*/
            loadAddressList:function(customerId) {
                var that = this;
                this.$send(this.getUrl('/product/customer/address/getByParentId/' + customerId),null,function (data) {
                    that.addressList = data;
                    //不影响编辑
                    if(that.saveDao.customerAddressId == null || that.saveDao.customerAddressId == 'null' ){
                        that.$set(that.saveDao,'customerAddressId',data[0].id);
                    }
                    that.changeAddress();
                });
            },
            /**选择地址改变电话联系人信息*/
            changeAddress:function() {

                for (let i = 0;i < this.addressList.length; i++) {
                    console.log('changeAddress222222');
                    let address = this.addressList[i];
                    if(this.saveDao.customerAddressId ==  address.id) {
                        //回写配送人 地址 电话等信息
                        this.$set(this.saveDao,'sendAddress',address.address);
                        this.$set(this.saveDao,'sendPhone',address.phone);
                        this.$set(this.saveDao,'sendName',address.name);
                    }
                }
            },
            /**选择型号改变内容*/
            changeModel:function(item) {
                for (var i=0;i<item.goodsModelList.length ; i++){
                    var model = item.goodsModelList[i];
                    if(item.goodsModelId ==  model.id) {
                        //更新列表
                        item.goodsModelName = model.name;
                        item.nowQuantity = model.quantity;
                        item.imgId = model.imgId;
                        item.contourName = model.contourName;
                    }
                }
            },
            /**删除本行*/
            deleteLine: function (index) {
                console.log('deleteLine: ' + index);
                if(confirm('确定删除此行？')){
                    this.infoDto.itemDaoList.splice(index,1);
                    this.updateBalance();
                }
            },
            selectedGoodsCallBack: function(goodsDao) {
                console.log('商品选择回调函数:'+goodsDao);
                //TODO 回写商品选择
                var that = this;
                this.$send(this.getUrl('/business/inventory/getGoodsModelInventory/' + goodsDao.id),null,function (data) {
                    var prePurchaseItem = {
                        goodsId:goodsDao.id,
                        goodsName:goodsDao.name,
                        venderName:goodsDao.venderName,
                        venderId:goodsDao.venderId,
                        quantity:0.00,
                        goodsModelList:data,
                        goodsModelId:data[0].id,
                        goodsModelName:data[0].name,
                        nowQuantity:data[0].quantity,
                        imgId:data[0].imgId,
                        contourName:data[0].contourName,
                    }
                    that.infoDto.itemDaoList.push(prePurchaseItem);
                    console.log('加入一条商品');
                    that.updateBalance();
                });
            },
            /**更新数据*/
            updateBalance:function() {
                var sum = 0;
                for (var i=0;i<this.infoDto.itemDaoList.length ; i++){
                    var item = this.infoDto.itemDaoList[i];
                    sum =  parseFloat(sum) + parseFloat(item.quantity);
                }
                this.$set(this.saveDao,'sumQuantity',sum);
            },
            /**根据id获取对应实体*/
            loadEditData:function(){
                //判断是否是修改
                if(sessionStorage.editId != null && sessionStorage.editId != 'null'){
                    console.log('editId=>'+sessionStorage.editId);
                    var that = this;
                    this.$send(this.queryUrl+sessionStorage.editId,null,function(data){
                        console.log('loadEditData成功！！'+JSON.stringify(data));
                        that.saveDao = data.orderDao;
                        that.infoDto = data;
                        that.loadAddressList(data.orderDao.customerId);
                        that.initItemData();
                    });
                    sessionStorage.editId = null;
                }
            },
            /**根据明细表中的数据,获取对应的详细信息*/
            initItemData:function(){
                var that = this;
                //加载对应的信息
                for (var j=0;j<this.infoDto.itemDaoList.length;j++) {
                    let item = this.infoDto.itemDaoList[j];
                    this.$send(this.getUrl('/product/goods/find/' + item.goodsId),null,function (goodsDao) {
                        that.$set(item,'goodsName',goodsDao.name);
                        that.$set(item,'venderName',goodsDao.venderName);
                        that.$send(that.getUrl('/business/inventory/getGoodsModelInventory/' + goodsDao.id),null,function (data) {
                            item.goodsModelList = data;
                            for(var i=0;i<data.length;i++){
                                if(data[i].id == item.goodsModelId) {
                                    that.$set(item,'goodsModelName',data[i].name);
                                    that.$set(item,'nowQuantity',data[i].quantity);
                                    that.$set(item,'imgId',data[i].imgId);
                                    that.$set(item,'contourName',data[i].contourName);
                                    break;
                                }
                            }
                        });
                    });
                }
            },
            /** 提交 */
            submit: function(state) {
                if(!this.submitCheck()){ //数据校验
                    return false;
                }
                this.saveDao.checkState = state;
                this.infoDto.orderDao = this.saveDao;
                //走提交流程
                var that = this;
                this.$send(this.submitUrl,this.infoDto,function(data){
                    console.log('执行成功！！'+JSON.stringify(data));
                    that.isShow = false;
                    alert("保存成功");
                });
            },
            /** 提交表单前的验证*/
            submitCheck:function(){
                for(var i=0;i<this.initSaveColumnList.length;i++){
                    if(this.initSaveColumnList[i].required){
                        var testValue = this.saveDao[this.initSaveColumnList[i].fieldName];
                        if(testValue == null || testValue == '' || testValue == undefined){
                            alert('非空校验失败:['+this.initSaveColumnList[i].title+'],请完善!!');
                            return false;
                        }
                    }
                }

                var itemList = this.infoDto.itemDaoList;
                if(itemList.length == 0) {
                    alert('至少录入一条数据!');
                    return false;
                }
                for (var j=0;j<itemList.length;j++) {
                    var item = itemList[j];
                    if (item.quantity == null || item.quantity == 0) {
                        alert('预定数量不可为空或零!');
                        return false;
                    }
                }
                return true;
            },

        },
        /**入参方法*/
        created: function () {
            this.init();
            var that_ = this;
            //重写图片选择回调方法
            Vue.prototype.selectedGoods = function(item){
                that_.selectedGoodsCallBack(item);
            };
        },
        mounted: function(){
            //重写客户自动下拉方法
            var that_ = this;
            console.log('加入组件！');
            Vue.prototype.$registerCustomerAuto('#customerName',function(dataValue,realValue) {
                that_.saveDao.customerId = realValue; //设置id的值
                that_.saveDao.customerName = dataValue; //设置id的值
                //更新地址列表
                that_.loadAddressList(that_.saveDao.customerId);
            });
        }

    });



</script>
